package leetcodev1.树;

import leetcodev1.链表.Solution;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class LeetCode95 {
    //我的思路
    //1.遍历所有排列组合
    //2.构造二叉搜索树
    //注意：213 231是同一种二叉树，因此需要去重

    //官方解
    //1.选择不同的数作为根节点，递归构造出二叉搜索树（有规律 左子树小于节点 右子树大于节点）
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> ret = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            ret.add(dfs(0, n));
        }
        return ret;
    }

    private TreeNode dfs(int left, int right) {
        if (left == right) {
            return new TreeNode(left);
        }

        for (int i = left; i <= right; i++) {
            TreeNode treeNode = new TreeNode(i);
            treeNode.left = dfs(left, i);
            treeNode.right = dfs(i, right);
            return treeNode;
        }

        return null;
    }
}

class Answer95 {
    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new LinkedList<TreeNode>();
        }
        return generateTrees(1, n);
    }

    public List<TreeNode> generateTrees(int start, int end) {
        List<TreeNode> allTrees = new LinkedList<TreeNode>();
        if (start > end) {
            allTrees.add(null);
            return allTrees;
        }

        // 枚举可行根节点
        for (int i = start; i <= end; i++) {
            // 获得所有可行的左子树集合
            List<TreeNode> leftTrees = generateTrees(start, i - 1);

            // 获得所有可行的右子树集合
            List<TreeNode> rightTrees = generateTrees(i + 1, end);

            // 从左子树集合中选出一棵左子树，从右子树集合中选出一棵右子树，拼接到根节点上
            for (TreeNode left : leftTrees) {
                for (TreeNode right : rightTrees) {
                    TreeNode currTree = new TreeNode(i);
                    currTree.left = left;
                    currTree.right = right;
                    allTrees.add(currTree);
                }
            }
        }
        return allTrees;
    }
}
